package cc.laop.business.system;

import cc.laop.business.BaseBusinessImpl;
import cc.laop.constants.UserConstants;
import cc.laop.dao.system.UserMapper;
import cc.laop.entity.system.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class UserBusiness extends BaseBusinessImpl<UserMapper, User> {

    @Autowired
    private ConfigBusiness configBusiness;

    public User getUserByEmail(String email) {
        User user = new User();
        user.setEmail(email);
        User dbuser = mapper.selectByNameOrEmail(user);
        return dbuser;
    }

    public int insertOrUpdate(User user) {
        int result = 0;
        if (user != null && user.getId() > 0) {
            User dbuser = super.selectOne(user.getId());
            if (dbuser != null) {
                dbuser.setUsername(user.getUsername());
                dbuser.setEmail(user.getEmail());
                dbuser.setPhone(user.getPhone());
                result = super.update(dbuser);
            } else {
                result = super.insert(user);
            }
        }
        return result;
    }

    /**
     * 更新用户角色
     *
     * @param userid
     * @param roleids
     */
    public void updateRole(int userid, String roleids) {
        mapper.deleteUserRole(userid);
        if (StringUtils.isNotEmpty(roleids)) {
            String[] ris = roleids.split(",");
            for (String id : ris) {
                if (StringUtils.isNumeric(id)) {
                    Map<String, Integer> map = new HashMap<String, Integer>();
                    map.put("userid", userid);
                    map.put("roleid", Integer.parseInt(id));
                    mapper.insertUserRole(map);
                }
            }
        }
    }

    public void delete(String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            String[] id = ids.split(",");
            super.delete(id);
        }
    }

    public int userSync(User user, String authCode, int type) {
        String localCode = configBusiness.getConfig(UserConstants.USER_SYNC_CODE);
        if (!localCode.equals(authCode)) {
            return 1;
        } else {
            if (type == UserConstants.USER_ADD) {
                super.insert(user);
            }
            if (type == UserConstants.USER_DELETE) {
                super.delete(user.getId());
            }
            if (type == UserConstants.USER_UPDATE) {
                super.update(user);
            }
            if (type == UserConstants.USER_BATCH) {
                insertOrUpdate(user);
            }
            return 0;
        }
    }

}
